#include<iostream>
using namespace std;
struct ListNode {
	int val;
	ListNode* next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode* next) : val(x), next(next) {}
};

class Solution {
public:
	ListNode* removeNthFromEnd(ListNode* head, int n) {
		if (head->next == nullptr)return nullptr;
		ListNode* cur = head;
		int cnt = 0;
		while (cur) {
			cnt++;
			cur = cur->next;
		}
		n = cnt - n;
		cur = head;
		ListNode* prev = nullptr;
		if (n == 0)return head->next;
		while (n--) {
			prev = cur;
			cur = cur->next;
		}
		prev->next = cur->next;
		delete cur;
		return head;
	}
};